package com.instpower.things.instpower;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName IdleTimeoutHandler
 * @Author: hellmash@gmail.com
 * @Date: 2020/2/24
 * @Version: 1.0.0
 * @Description: 超时处理
 */
@ChannelHandler.Sharable
public class IdleTimeoutHandler  extends ChannelDuplexHandler {
    private final static Logger logger = LoggerFactory.getLogger("SYS");
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception
    {
        logger.debug("触发器开始");
        if (evt instanceof IdleStateEvent)
        {
            logger.debug("获得触发器:{}" , ((IdleStateEvent) evt).state());
            IdleState e = ((IdleStateEvent) evt).state();
            if (e == IdleState.ALL_IDLE)
            {
                logger.debug("触发器处理开始，关闭连接!");
                ConnectionManager.getInstance().find(ctx).close();
                //服务端强制断开连接
                ctx.fireChannelInactive();
                ctx.close();
            }
        }
        else
        {
            super.userEventTriggered(ctx, evt);
        }
    }
}
